<template>
  <div class="login">
    <div class="header">
      <div class="logo"><img src="../../src/assets/image/login/logo.png"></div>
      <div class="service">帮助中心</div>
    </div>
    <div class="login-wrapper">
      <div class="content-wrapper">
        <div class="right-content">
          <div class="login-box">
            <div class="login-header">
              <div class="login-title">用户登录</div>
            </div>
            
            <!-- 登录方式切换 -->
            <div class="login-type">
              <div 
                :class="['type-item', activeType === 'account' ? 'active' : '']" 
                @click="switchLoginType('account')"
              >
                账号登录
              </div>
              <div 
                :class="['type-item', activeType === 'sms' ? 'active' : '']" 
                @click="switchLoginType('sms')"
              >
                验证码登录
              </div>
            </div>
            
            <!-- 账号登录表单 -->
            <div v-show="activeType === 'account'" class="input-wrapper">
              <div class="username-input-wrapper">
                <el-input
                  v-model="userAccount"
                  maxlength="11"
                  placeholder="用户名/手机号"
                  @keydown.enter="toLogin"
                >
                  <template #prefix>
                    <img src="../assets/image/login/ren.png" alt="用户" class="input-icon">
                  </template>
                </el-input>
              </div>
              <div class="code-input-wrapper">
                <el-input
                  v-model="code"
                  maxlength="20"
                  placeholder="密码"
                  type="password"
                  @keydown.enter="toLogin"
                >
                  <template #prefix>
                    <img src="../assets/image/login/suo.png" alt="密码" class="input-icon">
                  </template>
                </el-input>
              </div>
            </div>
            
            <!-- 短信验证码登录表单 -->
            <div v-show="activeType === 'sms'" class="input-wrapper">
              <div class="username-input-wrapper">
                <el-input
                  v-model="userPhone"
                  maxlength="11"
                  placeholder="请输入手机号"
                  @keydown.enter="toLogin"
                >
                  <template #prefix>
                    <i class="el-icon-mobile-phone input-icon-font"></i>
                  </template>
                </el-input>
              </div>
              <div class="code-input-wrapper sms-code-wrapper">
                <el-input
                  v-model="smsCode"
                  maxlength="6"
                  placeholder="请输入验证码"
                  @keydown.enter="toLogin"
                >
                  <template #prefix>
                    <i class="el-icon-message input-icon-font"></i>
                  </template>
                </el-input>
                <div class="send-code-btn" @click="sendCode" :class="{ 'disabled': countdownTimer < 60 }">
                  {{ countdownTimer < 60 ? `${countdownTimer}秒后重试` : '发送验证码' }}
                </div>
              </div>
            </div>
            
            <div class="login-btn-wrapper">
              <div class="login-btn btn" @click="toLogin()">登 录</div>
            </div>
            
            <!-- <div class="hint-text">
              温馨提示：学生用户，用户名和初始密码均为准考证号；家长用户，请使用注册时的手机号登录。
            </div> -->
            
            <!-- 错误提示框 -->
            <div class="error-tooltip" v-show="showHint">{{ hintText }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 页脚 -->
    <div class="footer">
      <div class="footer-content">
        <div class="motto">逐梦前行，铸就未来！</div>
        <div class="record-info">
          <a href="https://beian.miit.gov.cn/" style="color: #ccc;">冀ICP备2024088424号-1</a> 
          <span class="police-icon">
            <!-- <img src="../assets/image/login/police-icon.png" alt="公安备案" class="police-img"> -->
          </span> 
           邯郸宏合教育科技有限公司 版权所有
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { prefix } from '@/utils/constant';
import { mapGetters, mapMutations, mapActions } from 'vuex';
export default {
  data() {
    return {
      activeType: 'account', // 默认账号登录
      userAccount: '',
      code: '',
      userPhone: '',
      smsCode: '',
      countdownTimer: 60,
      showHint: false,
      hintText: '',
      timer: null,
      currentYear: new Date().getFullYear(),
    };
  },
  computed: {
    ...mapGetters('user', ['userId', 'isSuperAdmin']),
  },
  async mounted() {
    this.SET_USER_INFO({ value: {} });
    // 重置学校相关状态，确保不使用之前用户的学校数据
    this.RESET_SCHOOL();
    
    const {
      query: { userId, sessionId, userName },
    } = this.$route;
    if (!(userId && sessionId && userName)) {
      this.autoFillUserAccount();
    } else {
      this.setIsFromExamWeb({ value: true });
      const params = {
        userId,
        sessionId,
        userName,
      };
      this.SET_ACCOUNT_INFO({ value: params });
      const infoRes = await this.getUserInfo(userId);
      if(infoRes) {
        // 获取菜单后再跳转
        await this.loadUserMenus();
        // 获取第一个菜单路径并跳转
        const menuTree = this.$store.state.user.menuTree;
        const firstMenuPath = this.findFirstMenuPath(menuTree);
        if (firstMenuPath) {
          // 更新 sessionStorage，确保顶部导航栏正确选中菜单
          sessionStorage.setItem('lastSelectedMenu', firstMenuPath);
          this.$router.replace(firstMenuPath);
        } else {
          this.$router.replace('/homepage');
        }
      }
    }
  },
  beforeUnmount() {
    clearInterval(this.timer);
  },
  watch: {
    countdownTimer() {
      if (this.countdownTimer === 0) {
        clearInterval(this.timer);
        this.countdownTimer = 60;
      }
    },
  },
  methods: {
    ...mapMutations('user', ['SET_ACCOUNT_INFO', 'SET_USER_INFO']),
    ...mapMutations('base', ['setIsFromExamWeb']),
    ...mapActions('school', ['RESET_SCHOOL']),
    switchLoginType(type) {
      this.activeType = type;
      if (type === 'account') {
        this.userPhone = this.userAccount; // 同步账号
      } else {
        this.userAccount = this.userPhone; // 同步手机号
      }
    },
    autoFillUserAccount() {
      const userAccount = sessionStorage.getItem(`${prefix}account`);
      this.userAccount = userAccount || '';
      this.userPhone = userAccount || '';
    },
    toCountdown() {
      this.countdownTimer = 59;
      this.timer = setInterval(() => {
        this.countdownTimer--;
      }, 1000);
    },
    async sendCode() {
      if (this.countdownTimer < 60) return; // 倒计时期间不可点击
      
      if (this.userPhone.length === 0) {
        this.toShowHint('请输入手机号码');
        return;
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.userPhone)) {
        this.toShowHint('请输入正确的手机号码');
        return;
      }
      
      const { F_responseNo, F_responseMsg } = await this.$api.sendPhoneCode({
        F_phone: this.userPhone,
      });
      if (F_responseNo === 10000) {
        this.toCountdown();
        this.toShowHint('验证码已发送至您的手机', 1500);
      } else {
        this.toShowHint(F_responseMsg);
      }
    },
    async toLogin() {
      let loginRes;
      
      if (this.activeType === 'account') {
        if (!this.checkAccountInput()) return;
        loginRes = await this.tryAccountLogin();
      } else {
        if (!this.checkSmsInput()) return;
        loginRes = await this.trySmsLogin();
      }
      
      if (!loginRes) return;
      
      // 保存账号信息到Vuex
      this.SET_ACCOUNT_INFO({ value: loginRes });

      // 超级管理员直接进入首页（菜单会在路由守卫中加载）
      if (this.isSuperAdmin) {
        // 先获取菜单，再跳转
        await this.loadUserMenus();
        // 获取第一个菜单路径并跳转
        const menuTree = this.$store.state.user.menuTree;
        const firstMenuPath = this.findFirstMenuPath(menuTree);
        if (firstMenuPath) {
          // 更新 sessionStorage，确保顶部导航栏正确选中菜单
          sessionStorage.setItem('lastSelectedMenu', firstMenuPath);
          this.$router.push(firstMenuPath);
        } else {
          this.$router.push('/homepage');
        }
        return;
      }
      
      // 非超级管理员，需获取用户权限和菜单
      const res = await this.getUserInfo();
      if (res) {
        // 获取菜单后再跳转
        await this.loadUserMenus();
        // 获取第一个菜单路径并跳转
        const menuTree = this.$store.state.user.menuTree;
        const firstMenuPath = this.findFirstMenuPath(menuTree);
        if (firstMenuPath) {
          // 更新 sessionStorage，确保顶部导航栏正确选中菜单
          sessionStorage.setItem('lastSelectedMenu', firstMenuPath);
          this.$router.push(firstMenuPath);
        } else {
          this.$router.push('/homepage');
        }
      }
    },
    // 加载用户菜单和权限
    async loadUserMenus() {
      try {
        // 获取完整的菜单树（包含所有子菜单和按钮权限）
        // fetchAllButtonPermissions 已经返回了完整的树形结构，不需要再调用 fetchUserMenus
        await this.$store.dispatch('user/fetchAllButtonPermissions');
      } catch (error) {
        console.error('加载菜单或权限失败:', error);
        const errorMsg = error?.message || '加载菜单或权限失败，请稍后重试';
        this.$toast(errorMsg);
        throw error; // 抛出错误，阻止登录流程继续
      }
    },
    // 查找第一个有 menu_path 的菜单项（递归查找）
    findFirstMenuPath(menuTree) {
      if (!menuTree || !Array.isArray(menuTree) || menuTree.length === 0) {
        return null;
      }
      
      for (const menu of menuTree) {
        // 只处理菜单项类型（menu_type === 1），忽略功能按钮（menu_type === 2）
        if (menu.menu_type === 1 && menu.menu_path) {
          return menu.menu_path;
        }
        
        // 如果有子菜单，递归查找
        if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
          const childPath = this.findFirstMenuPath(menu.children);
          if (childPath) {
            return childPath;
          }
        }
      }
      
      return null;
    },
    checkAccountInput() {
      if (this.userAccount.length === 0) {
        this.toShowHint('请输入用户名/手机号');
        return false;
      }
      if (this.code.length === 0) {
        this.toShowHint('请输入密码');
        return false;
      }
      return true;
    },
    checkSmsInput() {
      if (this.userPhone.length === 0) {
        this.toShowHint('请输入手机号');
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(this.userPhone)) {
        this.toShowHint('请输入正确的手机号码');
        return false;
      }
      if (this.smsCode.length === 0) {
        this.toShowHint('请输入验证码');
        return false;
      }
      if (this.smsCode.length !== 6) {
        this.toShowHint('请输入6位验证码');
        return false;
      }
      return true;
    },
    // 账号登录验证方法
    async tryAccountLogin() {
      try {
        const formData = new FormData();
        formData.append('userAccount', this.userAccount);
        formData.append('password', this.code);
        formData.append('loginType', 'account'); // 登录类型：账号密码登录
        formData.append('machineSerial', 'teach_sys');
        
        // 调用统一的登录API
        const { F_responseNo, F_responseMsg, F_data } = await this.$api.login(
          formData
        );
        if (F_responseNo !== 10000) {
          this.toShowHint('登录失败:' + F_responseMsg, 1500);
          return false;
        }
        return F_data;
      } catch (e) {
        console.error(e);
        this.toShowHint('登录失败,请核对用户名或密码', 1500);
        return false;
      }
    },
    // 验证码登录验证方法
    async trySmsLogin() {
      try {
        const formData = new FormData();
        formData.append('userAccount', this.userPhone);
        formData.append('password', this.smsCode);
        formData.append('loginType', 'sms'); // 登录类型：验证码登录
        formData.append('machineSerial', 'teach_sys');
        
        // 调用统一的登录API
        const { F_responseNo, F_responseMsg, F_data } = await this.$api.login(
          formData
        );
        if (F_responseNo !== 10000) {
          this.toShowHint('登录失败:' + F_responseMsg, 1500);
          return false;
        }
        return F_data;
      } catch (e) {
        console.error(e);
        this.toShowHint('登录失败,请核对手机号码或验证码', 1500);
        return false;
      }
    },
    async getUserInfo() {
      try {
        const { F_data, F_responseNo, F_responseMsg } =
          await this.$api.getPermission({
            F_user_id: this.userId,
            F_sn: 'teach_sys',
          });
        if (F_responseNo === 10000) {
          const roleList = F_data.filter(e => !['科任老师', '科组长', '备课组长'].includes(e.role));
          if (roleList.length === 0) {
            this.$toast('该用户无法登录精准后台');
            return false;
          }
          let permission = roleList.find((e) => e.utype === 8);
          if (!permission) {
            permission = roleList.find((e) => e.utype === 4);
          }
          if(!permission) {
            this.$toast('该用户无法登录精准后台');
            return false;
          }
          this.SET_USER_INFO({ value: permission });
          return true;
        } else {
          this.$toast('无法登录精准后台:' + F_responseMsg);
          return false;
        }
      } catch (err) {
        console.error(err);
        this.$toast('获取用户权限失败, 请联系后台成员');
        return false;
      }
    },
    toShowHint(hintText, timeout = 1200) {
      this.hintText = hintText;
      this.showHint = true;
      setTimeout(() => {
        this.hintText = '';
        this.showHint = false;
      }, timeout);
    },
  },
};
</script>

<style>
html, body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow-y: auto !important;
}

#app {
  height: auto;
  min-height: 100vh;
  overflow-y: auto !important;
}
</style>

<style lang="less" scoped>
/* 重写全局样式确保滚动正常 */
.login {
  width: 100%;
  height: auto;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  position: relative;

  /* 头部样式 */
  .header {
    height: 56px;
    padding: 0 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    z-index: 99;
    border-bottom: 1px solid #f0f0f0;

    .logo {
      display: flex;
      align-items: center;
      height: 100%;
      
      img {
        width: 150px;
        height: auto;
        vertical-align: middle;
      }
    }

    .service {
      color: #40DBBC;
      font-size: 14px;
      font-weight: 500;
    }
  }

  /* 内容区域 */
  .login-wrapper {
    flex: 1;
    width: 100%;
    padding: 60px 0;
    background: url('../assets/image/login/backgroundimage.jpg') no-repeat;
    background-size: cover;
    background-position: center center;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: auto;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.05);
      z-index: 1;
    }

    .content-wrapper {
      width: 1200px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-right: 60px;
      position: relative;
      z-index: 2;

      .right-content {
        .login-box {
          width: 360px;
          min-height: 350px;
          padding: 30px 25px;
          background: #fff;
          border-radius: 6px;
          position: relative;
          box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);

          .login-header {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 25px;

            .login-title {
              font-size: 22px;
              color: #333;
              font-weight: 600;
              text-align: center;
              letter-spacing: 1px;
            }
          }
          
          // 登录方式切换标签
          .login-type {
            display: flex;
            border-bottom: 1px solid #EBEEF5;
            margin-bottom: 22px;
            
            .type-item {
              padding: 10px 0;
              margin-right: 25px;
              font-size: 15px;
              color: #606266;
              cursor: pointer;
              position: relative;
              transition: color 0.3s;
              
              &.active {
                color: #40DBBC;
                font-weight: 500;
                
                &::after {
                  content: '';
                  position: absolute;
                  bottom: -1px;
                  left: 0;
                  width: 100%;
                  height: 2px;
                  background-color: #40DBBC;
                }
              }
              
              &:hover {
                color: #40DBBC;
              }
            }
          }

          .input-wrapper {
            .username-input-wrapper,
            .code-input-wrapper {
              margin-bottom: 20px;
              position: relative;
            }
            
            .sms-code-wrapper {
              display: flex;
              
              .el-input {
                flex: 1;
              }
              
              .send-code-btn {
                margin-left: 10px;
                width: 110px;
                height: 40px;
                line-height: 40px;
                text-align: center;
                background: #40DBBC;
                color: #fff;
                font-size: 14px;
                border-radius: 4px;
                cursor: pointer;
                white-space: nowrap;
                transition: all 0.3s;
                
                &:hover {
                  opacity: 0.9;
                }
                
                &.disabled {
                  background: #DCDFE6;
                  cursor: not-allowed;
                }
              }
            }

            :deep(.el-input) {
              .el-input__prefix {
                left: 15px;
                height: 100%;
                display: flex;
                align-items: center;
              }

              .input-icon {
                width: 18px;
                height: 18px;
              }
              
              .input-icon-font {
                font-size: 18px;
                color: #909399;
              }

              .el-input__inner {
                height: 40px;
                line-height: 40px;
                padding-left: 45px;
                border-radius: 4px;
                
                &:focus {
                  border-color: #40DBBC;
                }
              }
            }
          }

          .login-btn {
            width: 100%;
            height: 40px;
            line-height: 40px;
            background: #40DBBC;
            color: #fff;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            text-align: center;
            transition: all 0.3s;
            margin: 28px 0 15px;
            letter-spacing: 1px;

            &:hover {
              opacity: 0.9;
              box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
              transform: translateY(-2px);
            }
          }

          .hint-text {
            margin: 15px 0;
            padding: 12px;
            font-size: 12px;
            color: #909399;
            line-height: 1.6;
            background-color: #F8F8F8;
            border-radius: 4px;
            border-left: 3px solid #E6E6E6;
          }
          
          .error-tooltip {
            position: absolute;
            top: -45px;
            left: 50%;
            transform: translateX(-50%);
            padding: 8px 15px;
            background: rgba(245, 108, 108, 0.9);
            color: #fff;
            font-size: 14px;
            border-radius: 4px;
            white-space: nowrap;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            z-index: 9999;
            animation: fadeInDown 0.3s;
            
            &::after {
              content: '';
              position: absolute;
              bottom: -6px;
              left: 50%;
              transform: translateX(-50%);
              width: 0;
              height: 0;
              border-left: 6px solid transparent;
              border-right: 6px solid transparent;
              border-top: 6px solid rgba(245, 108, 108, 0.9);
            }
          }
        }
      }
    }
  }

  /* 页脚样式 */
  .footer {
    width: 100%;
    height: 90px;
    background-color: #333;
    color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex-shrink: 0;
    margin-top: auto;
    
    .footer-content {
      width: 100%;
      text-align: center;
      
      .motto {
        font-size: 16px;
        margin-bottom: 15px;
        font-weight: 500;
        letter-spacing: 0.5px;
      }
      
      .record-info {
        font-size: 12px;
        color: #ccc;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
        letter-spacing: 0.3px;
        
        .police-icon {
          display: inline-flex;
          align-items: center;
          margin: 0 5px;
          
          .police-img {
            width: 18px;
            height: 18px;
          }
        }
      }
    }
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translate(-50%, -20px);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}
</style>
